package com.work.chat.custom.server.server.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.work.chat.common.util.StaticProperties;
import com.work.chat.custom.server.config.MybatisBeanFactory;
import com.work.chat.custom.server.config.model.BasePage;
import com.work.chat.custom.server.config.util.UserUtil;
import com.work.chat.custom.server.mapper.ProductMapper;
import com.work.chat.custom.server.pojo.dto.InsertProductDTO;
import com.work.chat.custom.server.pojo.entity.Product;
import com.work.chat.custom.server.pojo.vo.QueryProductVO;
import com.work.chat.custom.server.server.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private MybatisBeanFactory mybatisBeanFactory;
    @Autowired
    private UserUtil userUtil;


    @Override
    public IPage<QueryProductVO> queryProductPage(BasePage basePage) {
       IPage<QueryProductVO> iPage = new Page<>(basePage.getPage(),basePage.getPageSize());
        QueryWrapper<QueryProductVO> queryWrapper = mybatisBeanFactory.getQueryWrapper();
        queryWrapper.orderByAsc("id");
        IPage<QueryProductVO> productIPage = productMapper.selectListPage( queryWrapper,iPage);
        return productIPage;
    }

    @Override
    public void insertProduct(InsertProductDTO insertProductDTO) {
        LambdaQueryWrapper<Product> lambdaQueryWrapper = Wrappers.<Product>lambdaQuery()
                .eq(Product::getTypeId,insertProductDTO.getTypeId())
                .eq(Product::getProductCommodityCode,insertProductDTO.getProductCommodityCode());
        Product product = productMapper.selectOne(lambdaQueryWrapper);
        if (!ObjectUtils.isEmpty(product))
        {
            LambdaUpdateWrapper<Product> productLambdaUpdateWrapper  = mybatisBeanFactory.getLambdaUpdateWrapper();
            productLambdaUpdateWrapper.set(Product::getProductInventory,product.getProductInventory()+StaticProperties.ONELONG);
            productLambdaUpdateWrapper.eq(Product::getId,product.getId());
            productMapper.update(null,productLambdaUpdateWrapper);
        }
        else {
            product = new Product();
            BeanUtils.copyProperties(insertProductDTO,product);
            product.setProductInventory(StaticProperties.ONELONG);
            productMapper.insert(product);
        }
    }


}
